# -*- coding: utf-8 -*-
import traceback,sys
from django.core import exceptions
from django.conf import settings
from django.views.debug import technical_500_response
from django.http import HttpResponse,Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from apps.models import User
from apps.blog.models import Profile
from utils import logs
from utils.helper import view,convert

class PageBaseMiddleware:
    """
    summary:
        为Views的Request加入固定的东西
    author:
        李华顺 <huacnlee@gmail.com>
    """
    def process_request(self, request):
        # 取登录的用户信息
        request.is_logined = view.is_logined(request)
        request.current_profile = None

        if request.path.find('/user/admin/') >= 0:
            if not request.is_logined:
                return HttpResponseRedirect(reverse('signin'))
            
        try:
            request.current_profile = Profile.objects.get(user__id = view.get_current_user_id(request))
        except (User.DoesNotExist):
            view.login_out(request)
        except (Profile.DoesNotExist):
            view.login_out(request)
        except:
            view.login_out(request)
            logs.write(traceback)
            
        

        # 来源地址处理
        request.referer_url = '/'
        if not request.POST:
            view.set_session_val(request,'referer_url',request.META.get('HTTP_REFERER','/'))
        else:
            request.referer_url = view.get_session_val(request,'referer_url','/')

        # 用户IP地址
        request.client_ip = request.META['REMOTE_ADDR']
        

class FirebugMiddleware(object):
    """
    summary:
        This middleware allows you to easily include the excellent debugging tool Firebug Lite in your projects. To install it, 
        just add the middleware class to your list of installed middleware, pretty much anywhere in the list. If DEBUG is True, 
        and your IP address is in the list of INTERNAL_IPS, Firebug Lite will load. It will, however, only load in browsers that 
        are not Firefox, as I'm assuming that you have the real Firebug installed in Firefox. If you don't, go install it--what's 
        wrong with you?
        Check out http://getfirebug.com/lite.html for more information. 
    author:
        jfw <http://www.djangosnippets.org/users/jfw/>
    """
    def __init__(self):
        if not settings.DEBUG:
            raise exceptions.MiddlewareNotUsed

        try:
            self.firebug_url = settings.FIREBUG_URL
        except AttributeError:
            self.firebug_url = 'http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'

    def process_response(self, request, response):
        if (request.META['REMOTE_ADDR'] in settings.INTERNAL_IPS):
            index = response.content.lower().find('</script>') + len('</script>')
            if index != -1:
                response.content = '\n'.join([response.content[:index],self.firebug_html, response.content[index:]])
        return response

    @property
    def firebug_html(self):
        return '<script type="text/javascript" src="%s"></script>' % (self.firebug_url)
